<?php

/**
 * 缓存类
 *
 */

class Cache {

  var $config = array();

  function __construct($config=array()) {
    $this->config['cache_dir']   = '';
    $this->config['cache_file']  = 'dbcaches.php';
    $this->config['cache_time']  = 24 * 60;
    $this->config['json_file']   = 'dbcaches.json';
    $this->setconfig($config);
  }

  function __destruct() {

  }

  function setconfig($config=array()) {
    if (!empty($config) && is_array($config)){
      foreach($config as $key=>$value) {
        $this->config[$key] = $value;
      }
    }
  }

  function get($key) {
    return $this->config[$key];
  }
  
  function getcache($key='*') {
    $cachefile = $this->config['cache_dir'] . $this->config['cache_file'];
    if(file_exists($cachefile)) {
      $content = unserialize(file_get_contents($cachefile));
      if($key=='*') {
        return $content;
      }
      else {
        return $content[$key];
      }
    }
  }

  function setcache($arr=array(), $toggle='') {
    $cachefile = $this->config['cache_dir'] . $this->config['cache_file'];
    if($toggle or $this->config['cache_time']==-1) {
      $arr['expireTime'] = time();
      $content = serialize($arr);
      if ($this->makepath($cachefile) !== true) { exit('can\'t create dbcaches'); }
      file_put_contents($cachefile, $content);
    }
    else {
      $oldcontent = $this->getcache('*');
      $expireTime = (int)$oldcontent['expireTime'];
      if($this->config['cache_time']!=0 AND (time()-$expireTime > $this->config['cache_time'] * 60)) {
        $arr['expireTime'] = time();
        $content = serialize($arr);
        if ($this->makepath($cachefile) !== true) { exit('can\'t create dbcaches'); }
        file_put_contents($cachefile, $content);
      }
    }
  }

  function set($key, $val, $toggle='') {
    if (!$content = $this->getcache('*')) {
      $content = array();
    }
    $content[$key] = $val;
    $this->setcache($content, $toggle);
  }

  
  function savejson($arr) {
    $cachefile = $this->config['cache_dir'] . $this->config['json_file'];
    $content = json_encode($arr);
    if ($this->makepath($cachefile) !== true) { exit('can\'t create dbcaches'); }
    file_put_contents($cachefile, $content);
  }
  
  function getjson() {
    $cachefile = $this->config['cache_dir'] . $this->config['json_file'];
    if(file_exists($cachefile)) {
      $content = json_decode(file_get_contents($cachefile),true);
      return $content;
    }
    else {
      return array();
    }
  }

  function makepath($path) {
    $dirs = explode('/', dirname($path));
    $tmp = '';
    foreach ($dirs as $dir) {
      $tmp .= $dir . '/';
      if (!file_exists($tmp) && !@mkdir($tmp, 0777))
        return $tmp;
    }
    return true;
  }

}

?>